import 'dart:io';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/model/get_chapter_model.dart';
import 'package:appflutterhomeschool/model/student_information_model.dart';
import 'package:appflutterhomeschool/model/templates_model.dart';
import 'package:appflutterhomeschool/res/styles.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/ui/pages/notice/new/get_chapter_page.dart';
import 'package:appflutterhomeschool/ui/widgets/general_page_jump_widget.dart';
import 'package:appflutterhomeschool/view_model/my_app_view_model.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

///用户： ninetailedfox
///时间： 2020/6/21
///邮箱： 1037438704@qq.com
///功能： 创建通知，表单，讨论等页面
class CustumNotificationsViewModel extends ChangeNotifier {
  bool agreeBool = false;
  TemplatesModel templatesModel;
  bool receivingConfirmation = false;
  String rightContent = "未添加";

  //系统推荐作业
  String homworkSum;
  List<ChapteModel> titleContent = [
    ChapteModel(
      choice: true,
      select: true,
    ),
    ChapteModel(
      choice: false,
      select: true,
    ),
  ];

  BuildContext me;
  int pageTag;
  String titleBar;
  List<String> imageUrlList = [];
  TextEditingController titleText = TextEditingController();
  TextEditingController textContent = TextEditingController();

  /// 初始化的日期
  DateTime initDateTime;
  String imageUrl = "fabu_tupian";

  //是否展示点击添加系统作业的组件
  bool addSystemJob = false;

  //展示时间
  String visitionDate = "";

  CustumNotificationsViewModel(this.me, {this.pageTag, this.templatesModel});

  MyAppViewModel myAppViewModel;

  initView() {
    myAppViewModel = Provider.of(me);
    initDateTime = DateTime.now();
    switch (pageTag) {
      case 0:
        titleBar = "新建通知";
        receivingConfirmation = true;
        if (templatesModel != null) {
          titleText.text = templatesModel.title;
          textContent.text = templatesModel.msg;
        }
        break;
      case 1:
        titleBar = "新建讨论";
        break;
      case 2:
        titleBar = "新建任务";
        receivingConfirmation = true;
        break;
      case 3:
        titleBar = "新建信件";
        imageUrl = "fujian";
        break;
      case 4:
        titleBar = "发布作业";
        addSystemJob = true;
        break;
      default:
        titleBar = "";
        break;
    }
    notifyListeners();
  }

  ImagePicker picker = ImagePicker();

  Future getImage(index) async {
    if (index == 2) return;
    PickedFile pickedFile = await ImagePicker().getImage(
        source: index == 0 ? ImageSource.camera : ImageSource.gallery);
    File imageFile = File(pickedFile.path);
    //图片上传 获取链接
    DioUtils.getInstance().uploadFile(imageFile).then((value) {
      imageUrlList.add(value['file_url']);
      notifyListeners();
    });
  }

  //时间选择
  Widget dataItemWidget() {
    return Visibility(
      visible: pageTag == 1,
      child: GeneralPageJumpWidget(
        title: "开始时间：",
        textTitleStyle: TextStyles.textGray37,
        rightContent: visitionDate,
        textRightStyle: TextStyles.textDark37,
        onTap: () {
          PromptDialogWidgets(me).dateButtomDialog(
              dateTime: initDateTime,
              onConfirm: (dateTime) {
                initDateTime = dateTime;
                visitionDate =
                    '${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}\t${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
                notifyListeners();
              });
        },
      ),
    );
  }

  Widget pictureItemWidget() {
    return Visibility(
      visible: pageTag == 2 || pageTag == 3 || pageTag == 4,
      child: GeneralPageJumpWidget(
        image: imageUrl,
        title: "选择照片：",
        textTitleStyle: TextStyles.textDark37,
        onTap: () => PromptDialogWidgets(me).showaFileDialog(getIndex: (index) {
          getImage(index);
        }),
      ),
    );
  }

  List<StudentModel> studentList;
  String student = "";

  initEvent(int tag) {
    switch (tag) {
      case 0:
        //添加收件人
        Application()
            .navigatePushToPage(me, Routes.recipientListPage, {}).then((value) {
          if (value != null) {
            studentList = value["list"];
            student = "";
            studentList.forEach((element) {
              student = "$student${element.name},";
            });
            student = student.substring(0, student.length - 1);
            notifyListeners();
          }
        });
        break;
      case 1:
        //添加系统作业
        Navigator.push(
            me,
            MaterialPageRoute(
                builder: (context) => GetChapterPage(
                    chapteList: titleContent,
                    homworkSum: homworkSum))).then((value) {
          if (value != null) {
            homworkSum = value["sum"];
            if (titleContent.first.name != null) {
              rightContent = "已添加";
            }
          }
          notifyListeners();
        });
        break;
    }
  }

  releaseOnTap() {
    String pathUrl;
    Map<String, dynamic> mapJson = {
      "receiver": studentList.map((v) => v.toJson()).toList(),
      //类型：String  必有字段  备注：标题
      "title": titleText.text,
      "msg": textContent.text,
      "sender_type": 'Teacher',
      //类型：String  必有字段  备注：发送者类型（默认Teacher）
      "receiver_type": "Student",
      //类型：String  必有字段  备注：接收者类型（默认为Student）
      "cls_mapping": myAppViewModel.studentInformationModel.classMappingId,
    };

    switch (pageTag) {
      case 0:
//    新建通知
        pathUrl = ApiService.notifications;
        //类型：String  必有字段  备注：是否需要确认（False/True）
        mapJson.putIfAbsent("need_confirm", () => agreeBool ? "True" : "False");
        mapJson.putIfAbsent("notification_type", () => "Notification");
        break;
      case 1:
//    新建讨论
        pathUrl = ApiService.chatRoomNotifications;
        mapJson.putIfAbsent(
            "start_time", () => initDateTime.millisecondsSinceEpoch);
        mapJson.putIfAbsent(
            "end_time", () => initDateTime.millisecondsSinceEpoch);
        mapJson.putIfAbsent("notification_type", () => "ChatRoom");
        break;
      case 2:
        pathUrl = ApiService.tasks;
//    新建任务
        //类型：String  必有字段  备注：班级映射
        mapJson.putIfAbsent("need_confirm", () => agreeBool ? "True" : "False");
        mapJson.putIfAbsent("notification_type", () => "Task");
        mapJson.putIfAbsent("img", () => imageUrlList.toList());
        break;
      case 3:
//    新建信件
        break;
      case 4:
//    发布作业
        pathUrl = ApiService.publishHomework;
        String chapterId;
        String sectionId;
        if (titleContent.first.name == null) {
          Fluttertoast.showToast(msg: "请选择章节");
          return;
        } else {
          chapterId = titleContent.first.id;
        }

        if (titleContent.last.name == null) {
          Fluttertoast.showToast(msg: "请选择章节");
          return;
        } else {
          print("===================${titleContent.last.name}");
          print("===================${titleContent.last.id}");
          print("===================${titleContent.last.order}");
          sectionId = titleContent.last.id;
        }

        if(homworkSum == null){
          Fluttertoast.showToast(msg: "请选择题目数量");
          return;
        }

        mapJson = {
          "num": homworkSum, //类型：String  必有字段  备注：系统题目数量
          "title": titleText.text,
          "content": textContent.text,
          "img": imageUrlList.toList(),
          "scope": {
            //类型：Object  必有字段  备注：系统作业范围
            "chapter_id": chapterId,
            //类型：String  必有字段  备注：章id
            "section_id": sectionId
            //类型：String  必有字段  备注：节id
          },
          "students": studentList.map((v) => v.toJson()).toList(),
          "cls_mapping_id":
              myAppViewModel?.studentInformationModel?.classMappingId
        };
        break;
      default:
        break;
    }
    Logger().d(mapJson);
    Dio2Utils.getInstance().post(pathUrl, mapJson, (successCallBack) {
      Fluttertoast.showToast(msg: successCallBack["message"]);
      Navigator.pop(me);
    }, (errorCallBack) {
      Fluttertoast.showToast(msg: errorCallBack);
    });
  }
}
